package com.cti.ftpservice.ftp;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.cti.ftpservice.utils.FtpWsManagerUtil;
import com.cti.ftpservice.vo.FTPOnixXmlAnalysisTaskInfoVo;
import com.ctibook.booksystem.ws.FtpFileInfoViewVo;
import com.ctibook.booksystem.ws.OnixXmlFileReadOnixBookBaseInfoVo;

public class FTPOnixXmlAnalysisWork implements  Runnable {
	
	private FTPOnixXmlAnalysisTaskInfoVo fTPOnixXmlAnalysisInfo;
	private static Log logger = LogFactory.getLog(FTPOnixXmlAnalysisWork.class);
	
	public FTPOnixXmlAnalysisWork(FTPOnixXmlAnalysisTaskInfoVo _fFtpOnixXmlAnalysisInfo){
		fTPOnixXmlAnalysisInfo=_fFtpOnixXmlAnalysisInfo;
	}
	
	public void run() {
		Object dealFileinfo=null;
		if(fTPOnixXmlAnalysisInfo==null)
			return;
		while ((dealFileinfo=fTPOnixXmlAnalysisInfo.getFirstObjectItem())!=null) {
			try {
				 OnixXmlFileReadOnixBookBaseInfoVo infoVo=null;
				 FtpFileInfoViewVo fileInfoViewVo=(FtpFileInfoViewVo)dealFileinfo;
				 logger.info("开始读取文件："+fileInfoViewVo.getFileName());
				//TODO 解析文件,并将解析结果存入数据库并更新文件记录解析状态,采用sax流方式进行解析大文件
				 infoVo=FtpWsManagerUtil.readOnixXmlFileCommonMethod(fileInfoViewVo.getId(),fileInfoViewVo.getLocalFtpFilePath(),fileInfoViewVo.getSaveRecordCount());
				if(infoVo!=null)
					FtpWsManagerUtil.saveOnixXmlFileReadOnixBookBaseInfoVo(infoVo);
				 fTPOnixXmlAnalysisInfo.adddealItem(dealFileinfo,true); 
				 logger.info("文件："+fileInfoViewVo.getFileName()+"解析成功");
				 if(fTPOnixXmlAnalysisInfo.getFinished()){
					 logger.info("Onix文件解析任务完成，共处理"+fTPOnixXmlAnalysisInfo.getDealCount()+"个文件");
					 return;
				 }
				 Thread.sleep(1000);
			} catch (Exception e) {
				if(dealFileinfo!=null){
					fTPOnixXmlAnalysisInfo.adddealItem(dealFileinfo,false);
					FtpFileInfoViewVo fileInfoViewVo=(FtpFileInfoViewVo)dealFileinfo;
				    logger.error("文件："+fileInfoViewVo.getFileName()+"解析出错:"+e.getCause().toString());
				}
				logger.error(Thread.currentThread().getName()+":"+e.getMessage());	
			}
		}
	}
}